#include "wifi_control.h"
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "esp_netif.h"
#include "esp_tls.h"
#include "esp_http_client.h"
#include "cJSON.h"

#include "def_board.h"

static const char *TAG = "API";
char output_buffer[2560] = {0};

/**
 * @brief: wifi 初始化
 * @param {void} *pvParameters
 * @return {*}
 * @author:
 */
void API_weather_today(void)
{
    esp_http_client_config_t config = {
        .url = "https://api.seniverse.com/v3/weather/now.json?key=S_PqNhnCZWnKve5Ja&location=luoyang&language=zh-Hans&unit=c",
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    // GET Request
    esp_http_client_set_method(client, HTTP_METHOD_GET);
    // 与目标主机创建连接，并且声明写入内容长度为0
    // 因为如果是post请求，会在报文的头部后面跟着要向服务器发送的数据
    // 而对于get方法，发送的内容都在URL里面，都在报文头部，不需要定义后面的部分，因此写入长度就是0
    esp_err_t err = esp_http_client_open(client, 0);
    if (err != ESP_OK)
    {
        ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
    }
    else
    {
        int content_length = esp_http_client_fetch_headers(client);
        if (content_length < 0)
        {
            ESP_LOGE(TAG, "HTTP client fetch headers failed");
        }
        else
        {
            int data_read = esp_http_client_read_response(client, output_buffer, 2560);
            if (data_read >= 0)
            {
                // 打印响应内容，包括响应状态，响应体长度及其内容
                ESP_LOGI(TAG, "HTTP GET Status = %llu", esp_http_client_get_content_length(client) /*获取响应状态信息*/);
                printf("data:%s\n", output_buffer);
                // 对接收到的数据作相应的处理
                cJSON *root = NULL;
                root = cJSON_Parse(output_buffer);
                if (root == NULL) // 判断转换是否成功
                {
                    printf("error");
                }
                else
                {
                    printf("success\n");
                    cJSON *cjson_item = cJSON_GetObjectItem(root, "results");
                    cJSON *cjson_results = cJSON_GetArrayItem(cjson_item, 0);
                    cJSON *cjson_now = cJSON_GetObjectItem(cjson_results, "now");
                    cJSON *cjson_temperature = cJSON_GetObjectItem(cjson_now, "temperature");

                    printf("temperature:%s\n", cjson_temperature->valuestring);
                }
            }
        }
    }
    esp_http_client_close(client);
    printf("close");
}
